const express = require('express');
const cors = require('cors');
const dotenv = require('dotenv');
const fileUpload = require('express-fileupload');
const path = require('path');

// 加载环境变量
dotenv.config();

// 初始化Express应用
const app = express();
const PORT = process.env.PORT || 3000;

// 配置中间件
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 配置文件上传
const uploadFolder = path.join(__dirname, process.env.UPLOAD_FOLDER || 'uploads');
app.use(fileUpload({
  limits: { fileSize: process.env.MAX_FILE_SIZE || 5000000 },
  createParentPath: true,
  uploadDir: uploadFolder
}));

// 确保上传目录存在
const fs = require('fs');
if (!fs.existsSync(uploadFolder)){
  fs.mkdirSync(uploadFolder, { recursive: true });
}

// 引入数据库连接
require('./db');

// 引入路由
const softwareRoutes = require('./routes/softwareRoutes');
const userRoutes = require('./routes/userRoutes');

// 定义API路由
app.get('/', (req, res) => {
  res.json({ message: '团星网后端服务已启动' });
});

// 使用路由
app.use('/api/software', softwareRoutes);
app.use('/api/users', userRoutes);

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ message: '服务器发生错误', error: err.message });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});